/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package food;

import entities.FoodsItem;
import entities.OderFood;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.AddToCartLocal;
import session.CategoryFoodsFacadeLocal;
import session.FoodsFacadeLocal;
import session.OderFoodFacadeLocal;
import session.OrderFoodDetailsFacadeLocal;

/**
 *
 * @author TANGQUOCTUAN
 */
public class ControllerFood extends HttpServlet {

    @EJB
    private OrderFoodDetailsFacadeLocal orderFoodDetailsFacade;
    @EJB
    private OderFoodFacadeLocal oderFoodFacade;
    @EJB
    private FoodsFacadeLocal foodsFacade;
    @EJB
    private CategoryFoodsFacadeLocal categoryFoodsFacade;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            HttpSession session = request.getSession(true);
            AddToCartLocal local;
            if (action.equals("DetailFood")) {
                Integer id = new Integer(request.getParameter("FoodID"));
                List detailfood = this.foodsFacade.detailFood(id);
                request.setAttribute("InfoDetailFood", detailfood);
                request.getRequestDispatcher("DetailFood.jsp").forward(request, response);
            } else if (action.equals("adminFood")) {
                List adminFood = this.foodsFacade.getAllFood();
                request.setAttribute("listFoodAdmin", adminFood);
                ServletContext contextloadfood = getServletContext();
                List A = this.categoryFoodsFacade.getAllCategory();
                contextloadfood.setAttribute("data", A);
                request.getRequestDispatcher("foodadmin.jsp").forward(request, response);
            } else if (action.equals("Edit")) {
                Integer id = new Integer(request.getParameter("txtid"));
                ServletContext context = getServletContext();
                List detailfood = this.foodsFacade.detailFood(id);
                context.setAttribute("updateFood", detailfood);
                ServletContext contextloadfood = getServletContext();
                List A = this.categoryFoodsFacade.getAllCategory();
                contextloadfood.setAttribute("data", A);
                request.getRequestDispatcher("updatefoodadmin.jsp").forward(request, response);
            } else if (action.equals("Delete")) {
                Integer id = new Integer(request.getParameter("txtid"));
                boolean rs = this.foodsFacade.deleteFood(id);
                List deletefood = this.foodsFacade.findAll();
                request.setAttribute("listFoodAdmin", deletefood);
                request.getRequestDispatcher("foodadmin.jsp").forward(request, response);
            } else if (action.equals("AddToCart")) {
                Integer id = new Integer(request.getParameter("id"));
//                AddToCartJNDI
                if (session.getAttribute("SHOPPINGCART") == null) {
                    Context context = new InitialContext();
                    local = (AddToCartLocal) context.lookup("AddToCartJNDI");
                } else {
                    local = (AddToCartLocal) session.getAttribute("SHOPPINGCART");
                }
                local.addItem(id);
                session.setAttribute("total", local.totalAmount());
                session.setAttribute("SHOPPINGCART", local);
                request.getRequestDispatcher("ListFood.jsp").forward(request, response);
            } else if (action.equals("DeleteFood")) {
                Integer id = new Integer(request.getParameter("id"));
                local = (AddToCartLocal) session.getAttribute("SHOPPINGCART");
                local.removeItem(id);
                session.setAttribute("total", local.totalAmount());
                session.setAttribute("SHOPPINGCART", local);
                request.getRequestDispatcher("addToCart.jsp").forward(request, response);
            } else if (action.equals("Next")) {
                if (session.getAttribute("SHOPPINGCART") == null) {
                    Context context = new InitialContext();
                    local = (AddToCartLocal) context.lookup("AddToCartJNDI");
                } else {
                    local = (AddToCartLocal) session.getAttribute("SHOPPINGCART");
                }
                Double total = (Double) session.getAttribute("total");
                String user = request.getParameter("user");
                Date time = new Date(request.getParameter("time"));
                double price = Double.valueOf(total);
                if (total == 0) {
                    response.sendRedirect("errorshopping.jsp");
                } else {
                    int oid = local.insertOrderFood(user, price, false);
                    local.insertOrderDetails(oid);
                    session.setAttribute("SHOPPINGCART", null);
                    response.sendRedirect("successshopping.jsp");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private AddToCartLocal lookupAddToCartLocal() {
        try {
            Context c = new InitialContext();
            return (AddToCartLocal) c.lookup("java:comp/env/AddToCart");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
